package com.dao;

import java.util.List;

import com.Entity.User;
import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.query.Query;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Repository;



@Repository("userDao")

public class UserDaoImpl implements UserDao {

@Autowired

private SessionFactory SessionFactory ;

private Session getSession() {

        return SessionFactory.getCurrentSession();

        }

@Override

public Integer insertUser(User user) {

        getSession().save(user);

        return null;

        }

@Override

public List<User>  login(User user) {

        String hql="select distinct u from User u where u.username=?0 and u.password=?1 ";

@SuppressWarnings("rawtypes")

        Query query =getSession().createQuery(hql);

                query.setParameter(0+"", user.getUsername());

                query.setParameter(1+"", user.getPassword());

// query.setFirstResult(1).setMaxResults(1);

//System.out.println(query.list().size());

@SuppressWarnings("unchecked")

        List<User> list= query.list();

        return list;

        }

@Override

    public int updateUser(User user) {

            String hql="update User u set username=?0,password=?1 ,age=?2 where id=?3 ";

@SuppressWarnings("rawtypes")

        Query query =getSession().createQuery(hql);

                query.setParameter(0+"", user.getUsername());

                query.setParameter(1+"", user.getPassword());

                query.setParameter(2+"", user.getAge());

                query.setParameter(3+"", user.getId());

                int result = query.executeUpdate();

                return result;

                }

@Override

    public int deleteUser(User user) {

            String hql="delete from User u where u.id=?0 ";

@SuppressWarnings("rawtypes")

        Query query =getSession().createQuery(hql);

                query.setParameter(0+"", user.getId());



                int result = query.executeUpdate();

                return result;

                }

@Override

public List<User> queryUsers() {

        String hql="select distinct u from User u  ";

@SuppressWarnings("rawtypes")

        Query query =getSession().createQuery(hql);

@SuppressWarnings("unchecked")

        List<User> list= query.list();

        return list;

        }

@Override

public User getById(int id) {

        String hql="select distinct u from User u  where u.id=?0";

@SuppressWarnings("rawtypes")

        Query query =getSession().createQuery(hql);

                query.setParameter(0+"", id);

@SuppressWarnings("unchecked")

        List<User> list_u=query.list();

        User  list=null;

        if(list_u.size()>0){

        list = list_u.get(0);

        }

        return list;

        }

        }